<?php
namespace app\common\utils\aliyun;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use app\common\model\VerificationCode;
use Darabonba\OpenApi\Models\Config;
use think\facade\Db;

class Sms
{
    private const APPKEY    = 'LTAI5tQQMjhQc5YznXYU69P2';
    private const APPSECRET = 'RRFqfZyOlxgMYrnYwaCoLqfuoBuu5l';
    private const TEMPLATE  = 'SMS_299790415';
    private const SIGNNAME  = '事成物流';
    
    public static function send($account = '', $code = '')
    {
        $config = new Config([
            "accessKeyId" => self::APPKEY,
            "accessKeySecret" => self::APPSECRET
        ]);
        $client = new Dysmsapi($config);
        $request = new SendSmsRequest();
        $request->phoneNumbers = $account;
        $request->signName = self::SIGNNAME;
        $request->templateCode = self::TEMPLATE;
        $request->templateParam = json_encode(['code' => strval($code)], JSON_UNESCAPED_UNICODE);
        
        try {
            //发送短信
            $response = $client->sendSms($request);
            if ($response->body->code == 'OK') {
                self::createVerificationCode($account, $code);
                return ['code' => 1, 'msg' => $response->body->requestId];
            } else {
                return ['code' => 0, 'msg' => $response->body->message];
            }
        } catch (TeaUnableRetryError $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    
    public static function createVerificationCode($account, $code)
    {
        $verificationCode = VerificationCode::where('account', $account)->find();
        if ($verificationCode) {
            $todayStartTime = strtotime(date("Y-m-d"));//当天0点
            if ($verificationCode['send_time'] <= $todayStartTime) {
                $count = 1;
            } else {
                $count = Db::raw('count+1');
            }
            $verificationCode->save([
                'send_time' => time(),
                'expire_time' => time() + 30 * 60,
                'code' => $code,
                'count' => $count
            ]);
        } else {
            VerificationCode::create([
                'account' => $account,
                'send_time' => time(),
                'code' => $code,
                'count' => 1,
                'expire_time' => time() + 30 * 60
            ]);
        }
    }
    
    public static function getVerificationCode($account = '', $length = 6)
    {
        if (empty($account)) {
            return false;
        }
        $currentTime = time();
        $maxCount = 10;
        $result = false;
        $findVerificationCode = VerificationCode::where('account', $account)->find();
        if (empty($findVerificationCode)) {
            $result = true;
        } else {
            $sendTime = $findVerificationCode['send_time'];
            $todayStartTime = strtotime(date('Y-m-d', $currentTime));
            if ($sendTime < $todayStartTime) {
                $result = true;
            } else if ($findVerificationCode['count'] < $maxCount) {
                $result = true;
            }
        }
        if ($result) {
            switch ($length) {
                case 4:
                    $result = rand(1000, 9999);
                    break;
                case 6:
                    $result = rand(100000, 999999);
                    break;
                case 8:
                    $result = rand(10000000, 99999999);
                    break;
                default:
                    $result = rand(100000, 999999);
            }
        }
        return $result;
    }
    
    // 验证短信验证码
    public static function checkVerificationCode($account, $code)
    {
        $findVerificationCode = VerificationCode::where('account', $account)->find();
        if ($findVerificationCode) {
            if ($findVerificationCode['expire_time'] > time()) {
                if ($code == $findVerificationCode['code']) {
                    VerificationCode::where('account', $account)->update(['code' => '']);
                } else {
                    return "验证码不正确!";
                }
            } else {
                return "验证码已经过期,请先获取验证码!";
            }
            
        } else {
            return "请先获取验证码!";
        }
        return "";
    }
    
}